package com.yonyou.crm.base.attrgroup.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.base.attrgroup.entity.AttrGroupVO;
import com.yonyou.crm.base.attrgroup.entity.AttrRelationVO;
import com.yonyou.crm.base.attrgroup.rmitf.IAttrGroupRmService;
import com.yonyou.crm.common.enumeration.entity.WhetherEnum;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;

@RestController
@RequestMapping(value = "/base/attrgroups")
public class AttrGroupCtrl {

	@Autowired
	private IAttrGroupRmService service;
	
	/**
	 * 查询属性组
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);

		@SuppressWarnings("unchecked")
		Page<AttrGroupVO> productPage = service.page(getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
		
		return ResponseUtil.getObject(productPage);
	}
	
	/**
	 * 属性组详情
	 * @param code
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}		
		
		return ResponseUtil.getObject(service.detail(id));
	}
	
	/**
	 * 新增属性组
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Object insert(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		AttrGroupVO vo = getAttrGroupVO(request);

		String validMsg = validator(vo);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}

		return ResponseUtil.getObject(service.insert(vo));
	}
	
	
	/**
	 * 修改属性组
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="{id}", method = RequestMethod.PUT)
	public Object update(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}
		
		AttrGroupVO vo = getAttrGroupVO(request);

		String validMsg = validator(vo);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
		
		vo.setId(id);
				
		return ResponseUtil.getObject(service.update(vo));
	}
	
	/**
	 * 是否被产品或产品分类引用
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="{id}/cited", method = RequestMethod.GET)
	public Object cited(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}
		
		JSONObject rObj = new JSONObject();

		Integer flag = service.isCitedByProductOrPrdtype(id) ? WhetherEnum.YES.getValue() : WhetherEnum.NO.getValue();
		rObj.put("flag", flag);
		
		return ResponseUtil.getObject(rObj);
	}
	
	/**
	 * 批量删除
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "batch", method = RequestMethod.DELETE)
	public Object batchDelete(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");		

		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		
		String[] ids = idsStr.split(",");
		
		if (ids.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		
		String message = service.batchDelete(ids);
		
		Page<AttrGroupVO> page = service.page(getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
		
		return ResponseUtil.getObject(page, PCCodeConstant.Success, message);
	}
	
	/**
	 * 批量停启用
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "state", method = RequestMethod.PUT)
	public Object batchUpdateEnableState(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");		

		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		
		String[] ids = idsStr.split(",");
		
		if (ids.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		
		Integer enableState = paramObj.getInt("enableState");
		
		if (enableState == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "停启用状态不能为空");
		}
		
		return ResponseUtil.getObject(service.batchUpdateEnableState(ids, enableState, getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap")));
	}
	
	/**
	 * 获得属性组参照列表
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value = "ref", method = RequestMethod.GET)
	public Object getRefList(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		
		if (paramObj != null) {
			//有分页信息返回分页列表
			if (paramObj.containsKey(HttpKeyConstant.Page) && paramObj.containsKey(HttpKeyConstant.PageSize)) {
				return ResponseUtil.getObject(service.getRefPage(getRequestPage(paramObj), null));
			}
		}
		
		List<AttrGroupVO> voList = service.getRefList(null);
		
		Page<AttrGroupVO> page = new Page<AttrGroupVO>();
		page.setData(voList);
		
		return ResponseUtil.getObject(page);
	}
	
	/**
	 * 获得选中的属性
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}/attrs/checked", method = RequestMethod.GET)
	public Object getCheckedAttr(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "属性组主键不能为空");
		}

		return ResponseUtil.getObject(service.getCheckedAttr(id));
	}
	
	/**
	 * 获得选中的属性值
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}/attrs/{attrid}/values/checked", method = RequestMethod.GET)
	public Object getCheckedAttr(@PathVariable("id") Long id, @PathVariable("attrid") Long attrId, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null || attrId == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "属性组主键或属性主键不能为空");
		}
		
		return ResponseUtil.getObject(service.getCheckedAttrValue(id, attrId));
	}
	
	private String validator(AttrGroupVO vo) {
		
		if (vo == null) {
			return "转换实体失败";
		}
		
		if (StringUtils.isBlank(vo.getName())) {
        	return  "名称不能为空";
		}
		
		if (vo.getAttrList() == null || vo.getAttrList().size() == 0) {
			return "至少包含一个属性";
		}
		
		return "";
	}
	
	private AttrGroupVO getAttrGroupVO(HttpServletRequest request) {
		
		Map<String, Class<?>> fieldClassMap = new HashMap<String, Class<?>>();
		fieldClassMap.put("attrList", AttrRelationVO.class);
		return RequestUtil.getVO(request, AttrGroupVO.class, fieldClassMap);
	}
	
	private Page<AttrGroupVO> getRequestPage(JSONObject paramObj) throws CrmMessageException {
		
		Integer page = paramObj.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);
		
		if (page == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}
		
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}
		
		return new Page<AttrGroupVO>(page, pageSize);
	}
}
